﻿using System;
using System.Drawing;
using System.Drawing.Text;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace Clock
{
    [StructLayout(LayoutKind.Sequential)]
    public struct RECT
    {
        private int _Left;
        private int _Top;
        private int _Right;
        private int _Bottom;
    }

    public partial class ClockForm : Form
    {
        [DllImport("user32.dll", SetLastError = true)]
        static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        [DllImport("user32.dll", SetLastError = true)]
        static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);

        [DllImport("user32.dll", SetLastError = true)]
        static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool GetWindowRect(HandleRef hwnd, out RECT lpRect);

        PrivateFontCollection fontCollection=new PrivateFontCollection();
        public ClockForm()
        {
            InitializeComponent();

            var clockPtr = FindWindow("Shell_TrayWnd", null);
            clockPtr = FindWindowEx(clockPtr, IntPtr.Zero, "TrayNotifyWnd", null);
            clockPtr = FindWindowEx(clockPtr, IntPtr.Zero, "TrayClockWClass", null);
            SetParent(Handle, clockPtr);

            Location=new Point(0,0);

            fontCollection.AddFontFile("digifaw.ttf");
            if(fontCollection.Families.Length>0)
            {
                //Font = new Font(fontCollection.Families[0], 7);
            }
        }

        private void ClockForm_DoubleClick(object sender, EventArgs e)
        {
            var dateForm=new DateForm();
            var x = Screen.PrimaryScreen.WorkingArea.Right-dateForm.Size.Width;
            var y = Screen.PrimaryScreen.WorkingArea.Bottom-dateForm.Size.Height;
            dateForm.Location=new Point(x,y);
            dateForm.ShowDialog(this);
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            
            var time=DateTime.Now.ToString("HH:mm");
            var date=DateTime.Now.ToString("yyy/MM/dd");
            var timeSize= e.Graphics.MeasureString(time, Font);
            var dateSize= e.Graphics.MeasureString(date, Font);
            e.Graphics.DrawString(time,Font,Brushes.Black,(e.ClipRectangle.Width-timeSize.Width)/2,(ClientSize.Height-timeSize.Height-dateSize.Height)/2);
            e.Graphics.DrawString(date, Font, Brushes.Black, (e.ClipRectangle.Width - dateSize.Width) / 2, (ClientSize.Height - timeSize.Height - dateSize.Height) / 2+timeSize.Height);
        }

        private void ClockTimer_Tick(object sender, EventArgs e)
        {
            Refresh();
        }
    }
}
